package com.shanzmoo.db.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shanzmoo.base.bean.SResponse;
import com.shanzmoo.base.util.ObjectUtils;
import com.shanzmoo.db.product.entity.ProductCategoryEntity;
import com.shanzmoo.db.product.entity.dto.CatsDto;
import com.shanzmoo.db.product.entity.dto.ProductCategoryDTO;
import com.shanzmoo.db.product.entity.vo.CategoryVo;
import com.shanzmoo.db.product.mapper.ProductCategoryMapper;
import com.shanzmoo.db.product.service.IProductCategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 商品分类 服务实现类
 * </p>
 *
 * @author Xueqz
 * @since 2020-12-07
 */
@Service
public class ProductCategoryServiceImpl extends ServiceImpl<ProductCategoryMapper, ProductCategoryEntity> implements IProductCategoryService {

    @Override
    public SResponse<List<CategoryVo>> getAllTree() {
        List<ProductCategoryEntity> productCategoryEntityList = baseMapper.selectList(new QueryWrapper<ProductCategoryEntity>()
                .eq("deleted", false));
        List<CategoryVo> categoryTree = getCategoryTree(productCategoryEntityList, 0,"顶级分类");
        return SResponse.ok(categoryTree);
    }

    @Override
    public List<CatsDto> getCatIdAndParents() {
        return baseMapper.getCatIdAndParents();
    }

    @Override
    public List<ProductCategoryDTO> getAllCategory() {
        return baseMapper.getAllCategory();
    }

    private List<CategoryVo> getCategoryTree(List<ProductCategoryEntity> productCategoryEntityList,Integer parentId,String parentName){
        List<CategoryVo> categoryVoList = new ArrayList<CategoryVo>();
        for (ProductCategoryEntity productCategoryEntity : productCategoryEntityList) {
            if(parentId.equals(productCategoryEntity.getParentId())){
                CategoryVo vo = ObjectUtils.convert(productCategoryEntity, CategoryVo.class);
                vo.setParentName(parentName);
                categoryVoList.add(vo);
            }
        }
        for (CategoryVo categoryVo : categoryVoList) {
            List<CategoryVo> categoryTree = getCategoryTree(productCategoryEntityList, categoryVo.getId(),categoryVo.getName());
            if(categoryTree != null && categoryTree.size() > 0){
                categoryVo.setChildren(categoryTree);
            }
        }
        return categoryVoList;
    }
}
